<template>
  <view class="apply-page">
    <view class="form-section">
      <view class="section-title">申请人信息</view>
      <view class="form-group">
        <view class="form-item">
          <text class="form-label required">姓名</text>
          <input v-model="formData.name" class="form-input" placeholder="请输入您的真实姓名" />
        </view>
        <view class="form-item">
          <text class="form-label required">性别</text>
          <view class="gender-select">
            <view
              class="gender-option"
              :class="{ active: formData.gender === '男' }"
              @click="formData.gender = '男'"
            >
              <text class="gender-icon">♂</text>
              <text>男</text>
            </view>
            <view
              class="gender-option"
              :class="{ active: formData.gender === '女' }"
              @click="formData.gender = '女'"
            >
              <text class="gender-icon">♀</text>
              <text>女</text>
            </view>
          </view>
        </view>
        <view class="form-item">
          <text class="form-label">出生日期</text>
          <picker
            mode="date"
            :value="formData.birthDate"
            start="1900-01-01"
            end="2025-12-31"
            @change="onBirthdayChange"
          >
            <view class="picker-value">
              <text>{{ formData.birthDate || "请选择出生日期时间" }}</text>
              <wd-icon name="arrow-down" size="32rpx" color="#999"></wd-icon>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">籍贯</text>
          <input v-model="formData.nativePlace" class="form-input" placeholder="请输入籍贯" />
        </view>
        <view class="form-item">
          <text class="form-label">民族</text>
          <input v-model="formData.ethnicity" class="form-input" placeholder="请输入民族" />
        </view>
        <view class="form-item">
          <text class="form-label">文化程度</text>
          <picker :value="educationIndex" :range="educationTypes" @change="onEducationChange">
            <view class="picker-value">
              <text>{{ formData.education || "请选择文化程度" }}</text>
              <wd-icon name="arrow-down" size="32rpx" color="#999"></wd-icon>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">政治面貌</text>
          <picker :value="politicalIndex" :range="politicalTypes" @change="onPoliticalChange">
            <view class="picker-value">
              <text>{{ formData.politicalStatus || "请选择政治面貌" }}</text>
              <wd-icon name="arrow-down" size="32rpx" color="#999"></wd-icon>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">专长</text>
          <input v-model="formData.specialty" class="form-input" placeholder="请输入专长" />
        </view>
        <view class="form-item">
          <text class="form-label">推荐人</text>
          <input v-model="formData.recommender" class="form-input" placeholder="请输入推荐人" />
        </view>
        <view class="form-item">
          <text class="form-label required">手机号码</text>
          <input
            v-model="formData.phone"
            class="form-input"
            type="number"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </view>
        <view class="form-item">
          <text class="form-label">身份证号码</text>
          <input
            v-model="formData.idCard"
            class="form-input"
            placeholder="请输入身份证号码"
            maxlength="18"
          />
        </view>
        <view class="form-item">
          <text class="form-label">通讯地址</text>
          <input v-model="formData.address" class="form-input" placeholder="请输入通讯地址" />
        </view>
      </view>
    </view>

    <view class="form-section">
      <view class="section-title">会员类型选择</view>
      <view class="form-group">
        <view class="form-item">
          <text class="form-label">会员类别</text>
          <picker :value="memberTypeIndex" :range="memberTypes" @change="onMemberTypeChange">
            <view class="picker-value">
              <text>{{ memberTypes[memberTypeIndex] || "请选择会员类别" }}</text>
              <wd-icon name="arrow-down" size="32rpx" color="#999"></wd-icon>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">拟任总会职务</text>
          <checkbox-group class="position-checkbox-group" @change="onPositionChange">
            <label
              v-for="(position, index) in positionTypes"
              :key="position.id"
              class="position-option"
            >
              <checkbox :value="position.id" color="#1989fa" />
              <text class="position-text">{{ position.name }}</text>
            </label>
          </checkbox-group>
        </view>
        <view v-if="formData.memberType === 'B' || formData.memberType === 'C'" class="form-item">
          <text class="form-label">企业名称</text>
          <input v-model="formData.companyName" class="form-input" placeholder="请输入企业名称" />
        </view>
        <view v-if="formData.memberType === 'B' || formData.memberType === 'C'" class="form-item">
          <text class="form-label">企业职务</text>
          <input v-model="formData.companyPosition" class="form-input" placeholder="请输入职务" />
        </view>
        <view v-if="formData.memberType === 'B' || formData.memberType === 'C'" class="form-item">
          <text class="form-label">企业注册资金</text>
          <input
            v-model="formData.registeredCapital"
            class="form-input"
            type="number"
            placeholder="请输入企业注册资金"
          />
        </view>
        <view v-if="formData.memberType === 'B' || formData.memberType === 'C'" class="form-item">
          <text class="form-label">企业地址</text>
          <input
            v-model="formData.companyAddress"
            class="form-input"
            placeholder="请输入企业地址"
          />
        </view>
        <view v-if="formData.memberType === 'B' || formData.memberType === 'C'" class="form-item">
          <text class="form-label">经营范围</text>
          <textarea
            v-model="formData.businessScope"
            class="form-textarea"
            placeholder="请输入经营范围"
            maxlength="500"
          ></textarea>
        </view>
      </view>
    </view>

    <view class="form-section">
      <view class="section-title">缴纳会费</view>
      <view class="form-group">
        <view class="form-item">
          <text class="form-label">缴纳金额</text>
          <text class="payment-amount">{{ formData.paymentAmount }} 元</text>
        </view>
        <view class="form-item">
          <text class="form-label required">到账时间</text>
          <picker
            mode="date"
            :value="formData.paymentTime"
            start="1900-01-01"
            end="2025-12-31"
            @change="onPaymentTimeChange"
          >
            <view class="picker-value">
              <text>{{ formData.paymentTime || "请选择到账日期时间" }}</text>
              <wd-icon name="arrow-down" size="32rpx" color="#999"></wd-icon>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">推荐人</text>
          <input
            v-model="formData.paymentRecommender"
            class="form-input"
            placeholder="请输入推荐人"
          />
        </view>
        <view class="form-item">
          <text class="form-label">收款码</text>
          <view class="qr-code-container">
            <image class="qr-code-image" src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png" mode="aspectFit" />
            <text class="qr-code-tip">请扫码支付会费</text>
          </view>
        </view>
        <view class="form-item">
          <text class="form-label required">支付凭证</text>
          <AvatarUploader v-model="formData.paymentProof" />
          <text class="upload-hint">请上传支付凭证截图，大小不超过5MB</text>
        </view>
      </view>
    </view>

    <view class="form-section">
      <view class="section-title">照片上传</view>
      <view class="form-group">
        <view class="form-item">
          <text class="form-label">个人照片</text>
          <AvatarUploader v-model="formData.photoUrl" />
          <text class="upload-hint">请上传证件照，大小不超过2MB</text>
        </view>
      </view>
    </view>

    <view class="form-section">
      <view class="section-title">申请人签名</view>
      <view class="form-group">
        <view class="form-item">
          <text class="form-label required">申请人</text>
          <input v-model="formData.applicant" class="form-input" placeholder="请输入申请人姓名" />
        </view>
        <view class="form-item">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-label">
              <checkbox value="agree" color="#1989fa" />
              <text class="agreement-text">我已阅读并同意《宗亲会章程》和《隐私条款》</text>
            </label>
          </checkbox-group>
        </view>
      </view>
    </view>

    <view class="button-group">
      <button class="btn-cancel" @click="cancel">取消</button>
      <button class="btn-submit" @click="submitForm">提交申请</button>
    </view>

    <!-- 提示弹窗 -->
    <view v-if="showPopup" class="popup-mask" @click="showPopup = false"></view>
    <view v-if="showPopup" class="popup-content">
      <view class="popup-title">提交成功</view>
      <view class="popup-message">{{ successMessage }}</view>
      <button class="popup-btn" @click="confirmSuccess">确定</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from "vue";
import ClanMember from "@/api/genealogy/clanMember";
import AvatarUploader from "@/components/AvatarUploader/AvatarUploader.vue";
import PositionAPI from "@/api/genealogy/position";
// 页面类型：apply-申请入会，join-加入宗亲会
const pageType = ref("apply");

// 页面标题
const pageTitle = computed(() => {
  return pageType.value === "join" ? "加入宗亲会" : "申请入会";
});

// 成功提示信息
const successMessage = computed(() => {
  return pageType.value === "join"
    ? "您已成功加入宗亲会，欢迎成为我们的一员！"
    : "您的宗亲会申请已提交成功，我们会尽快审核，请耐心等待通知。";
});

// 获取页面参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options || {};
  pageType.value = options.type || "apply";

  // 获取路由参数clanId
  const clanId = options.clanId || "";

  // 获取职位数据，传入clanId参数
  PositionAPI.getPositionPage({ pageNum: 1, pageSize: 20, clanAssociationId: clanId })
    .then((res) => {
      if (res && res.list) {
        positionTypes.value = res.list.map((item) => ({
          id: item.id,
          name: item.name,
          fee: item.fee,
          description: item.description,
        }));
        // 设置默认值
        if (positionTypes.value.length > 0) {
          selectedPositionIds.value = [];
          selectedPositionNames.value = [];
        }
      }
    })
    .catch(() => {
      // 如果接口失败，使用默认数据
      // positionTypes.value = [
      //   { id: 1, name: '会员' },
      //   { id: 2, name: '理事' },
      //   { id: 3, name: '常务理事' },
      //   { id: 4, name: '副会长' },
      //   { id: 5, name: '常务副会长' },
      //   { id: 6, name: '执行会长' }
      // ]
      // selectedPositionIds.value = []
      // selectedPositionNames.value = []
      // formData.positions = ''
    });
});

// 表单数据
const formData = reactive({
  name: "",
  gender: "男",
  birthDate: "",
  nativePlace: "",
  ethnicity: "",
  education: "",
  politicalStatus: "",
  specialty: "",
  recommender: "",
  phone: "",
  idCard: "",
  address: "",
  memberType: "A",
  companyName: "",
  position: [] as string[],
  companyPosition: "", // 企业职务
  registeredCapital: 0, // 企业注册资本
  companyAddress: "",
  businessScope: "",
  paymentAmount: 500,
  paymentTime: "",
  paymentRecommender: "",
  photoUrl: "",
  paymentProof: "",
  applicant: "",
});

// 协议同意状态
const agreement = ref(false);

// 文化程度选择
const educationTypes = ["小学", "初中", "高中", "大专", "本科", "硕士", "博士"];
const educationIndex = ref(0);

// 政治面貌选择
const politicalTypes = ["群众", "共青团员", "中共党员", "民主党派"];
const politicalIndex = ref(0);

// 会员类型选择
const memberTypes = ["A、文史会员", "B、联盟成员", "C、联盟企业"];
const memberTypeIndex = ref(0);

// 拟任总会职务选择
const positionTypes = ref<Array<{ id: string | number; name: string }>>([]);
const selectedPositionIds = ref<string[]>([]);
const selectedPositionNames = ref<string[]>([]);

// 弹窗控制
const showPopup = ref(false);

// 出生日期选择
const onBirthdayChange = (e: any) => {
  formData.birthDate = e.detail.value;
  console.log("选择的出生日期时间:", formData.birthDate);
};

// 文化程度选择
const onEducationChange = (e: any) => {
  educationIndex.value = e.detail.value;
  formData.education = educationTypes[e.detail.value];
};

// 政治面貌选择
const onPoliticalChange = (e: any) => {
  politicalIndex.value = e.detail.value;
  formData.politicalStatus = politicalTypes[e.detail.value];
};

// 会员类型选择
const onMemberTypeChange = (e: any) => {
  memberTypeIndex.value = e.detail.value;
  formData.memberType = memberTypes[memberTypeIndex.value].charAt(0);
  // 根据会员类型设置不同的会费金额
  if (formData.memberType === "A") {
    formData.paymentAmount = 500;
    selectedPositionIds.value = [];
    selectedPositionNames.value = [];
    formData.position = [];
  } else if (formData.memberType === "B") {
    formData.paymentAmount = 500;
    selectedPositionIds.value = ["B1"];
    selectedPositionNames.value = ["联盟成员"];
    formData.position = ["B1"];
  } else if (formData.memberType === "C") {
    formData.paymentAmount = 1000;
    selectedPositionIds.value = ["C1"];
    selectedPositionNames.value = ["联盟企业"];
    formData.position = ["C1"];
  }
};

// 拟任总会职务选择
// 职务选择
const onPositionChange = (e: any) => {
  const selectedIds = e.detail.value;
  selectedPositionIds.value = selectedIds.map((id) => String(id));
  // 根据选中的ID获取对应的职务名称

  console.log(positionTypes.value, 2222222222222);
  selectedPositionNames.value = positionTypes.value
    .filter((pos) => selectedIds.includes(String(pos.id)))
    .map((pos) => pos.name);
  // 直接存储ID数组
  formData.position = selectedPositionIds.value;
  // A类型会员根据职务调整会费
  if (formData.memberType === "A") {
    // 职务多选，取第一个职务的ID对应的名称作为计算依据
    const firstPositionId = selectedIds[0];
    const firstPosition = positionTypes.value.find(
      (pos) => String(pos.id) === String(firstPositionId)
    );
    const firstPositionName = firstPosition ? firstPosition.name : "";

    switch (firstPositionName) {
      case "会员":
        formData.paymentAmount = 500;
        break;
      case "理事":
        formData.paymentAmount = 2000;
        break;
      case "常务理事":
        formData.paymentAmount = 3000;
        break;
      case "副会长":
        formData.paymentAmount = 6000;
        break;
      case "常务副会长":
        formData.paymentAmount = 15000;
        break;
      case "执行会长":
        formData.paymentAmount = 25000;
        break;
      default:
        formData.paymentAmount = 500;
    }
  }
};

// 到账时间选择
const onPaymentTimeChange = (e: any) => {
  formData.paymentTime = e.detail.value;
  console.log("选择的到账时间:", formData.paymentTime);
};

// 协议同意
const onAgreementChange = (e: any) => {
  agreement.value = e.detail.value.length > 0;
};

// 取消
const cancel = () => {
  uni.navigateBack();
};

// 提交表单
const submitForm = () => {
  // 验证必填项
  if (!agreement.value) {
    return uni.showToast({ title: "请阅读并同意《宗亲会章程》和《隐私条款》", icon: "none" });
  }
  if (!formData.name) {
    return uni.showToast({ title: "请输入姓名", icon: "none" });
  }
  if (!formData.gender) {
    return uni.showToast({ title: "请选择性别", icon: "none" });
  }
  if (!formData.phone) {
    return uni.showToast({ title: "请输入手机号码", icon: "none" });
  }
  if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    return uni.showToast({ title: "手机号码格式不正确", icon: "none" });
  }
  if (!formData.paymentTime) {
    return uni.showToast({ title: "请选择到账日期时间", icon: "none" });
  }
  if (!formData.paymentProof) {
    return uni.showToast({ title: "请上传支付凭证", icon: "none" });
  }
  if (!formData.applicant) {
    return uni.showToast({ title: "请输入申请人姓名", icon: "none" });
  }

  // 保证 birthDate 和 paymentTime 字段带有 00:00:00 格式
  if (formData.birthDate && !/^\d{4}-\d{2}-\d{2} 00:00:00$/.test(formData.birthDate)) {
    formData.birthDate = formData.birthDate.trim().slice(0, 10) + " 00:00:00";
  }
  if (formData.paymentTime && !/^\d{4}-\d{2}-\d{2} 00:00:00$/.test(formData.paymentTime)) {
    formData.paymentTime = formData.paymentTime.trim().slice(0, 10) + " 00:00:00";
  }

  // 显示提交中
  uni.showLoading({ title: "提交中..." });
  // 根据页面类型调用不同的接口
  if (pageType.value === "join") {
    // 加入宗亲会 - 调用 addClanMember 接口
    ClanMember.addClanMember(formData)
      .then((res) => {
        uni.hideLoading();
        showPopup.value = true;
      })
      .catch((error) => {
        uni.hideLoading();
        uni.showToast({
          title: "加入宗亲会失败",
          icon: "error",
        });
      });
  } else {
    // 申请入会 - 调用 apply 接口
    ClanMember.apply(formData)
      .then((res) => {
        uni.hideLoading();
        showPopup.value = true;
      })
      .catch((error) => {
        uni.hideLoading();
        uni.showToast({
          title: "申请提交失败",
          icon: "error",
        });
      });
  }
};

// 确认成功
const confirmSuccess = () => {
  showPopup.value = false;
  uni.navigateBack();
};
</script>

<style lang="scss">
.position-option {
  width: 50%;
  display: inline-block;
}
.apply-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40rpx;
  padding-top: 20rpx;
  position: relative;
}

.form-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      left: 0;
      bottom: -10rpx;
      width: 60rpx;
      height: 4rpx;
      background-color: #1989fa;
      border-radius: 2rpx;
    }
  }
}

.form-group {
  .form-item {
    margin-bottom: 30rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;

    &.required::before {
      content: "*";
      color: #f56c6c;
      margin-right: 6rpx;
    }
  }

  .form-input {
    width: 100%;
    height: 80rpx;
    background-color: #f5f7fa;
    border-radius: 8rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    color: #333;
  }

  .gender-select {
    display: flex;

    .gender-option {
      flex: 1;
      height: 80rpx;
      background-color: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      border-radius: 8rpx;

      &:last-child {
        margin-right: 0;
      }

      &.active {
        background-color: rgba(25, 137, 250, 0.1);
        color: #1989fa;
      }

      .gender-icon {
        margin-right: 10rpx;
        font-weight: bold;
      }
    }
  }

  .picker-value {
    width: 100%;
    height: 80rpx;
    background-color: #f5f7fa;
    border-radius: 8rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #333;
  }

  .textarea-item {
    position: relative;
  }

  .form-textarea {
    width: 100%;
    height: 200rpx;
    background-color: #f5f7fa;
    border-radius: 8rpx;
    padding: 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    color: #333;
    line-height: 1.5;
  }

  .textarea-counter {
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
    font-size: 24rpx;
    color: #999;
  }

  .upload-area {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20rpx;
  }

  .upload-item,
  .upload-add {
    width: 180rpx;
    height: 180rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    overflow: hidden;
    position: relative;
  }

  .upload-image {
    width: 100%;
    height: 100%;
  }

  .upload-delete {
    position: absolute;
    right: 0;
    top: 0;
    width: 40rpx;
    height: 40rpx;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .upload-add {
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1rpx dashed #dcdfe6;

    .add-icon {
      font-size: 60rpx;
      height: 60rpx;
      line-height: 60rpx;
      color: #c0c4cc;
      margin-bottom: 10rpx;
    }

    .add-text {
      font-size: 24rpx;
      color: #909399;
    }
  }

  .upload-hint {
    font-size: 24rpx;
    color: #909399;
  }
}

.button-group {
  padding: 0 30rpx 50rpx;
  display: flex;
  justify-content: space-between;

  .btn-cancel,
  .btn-submit {
    width: 45%;
    height: 90rpx;
    line-height: 90rpx;
    border-radius: 45rpx;
    font-size: 32rpx;
  }

  .btn-cancel {
    background-color: #fff;
    color: #606266;
    border: 1rpx solid #dcdfe6;
  }

  .btn-submit {
    background-color: #1989fa;
    color: #fff;

    &:disabled {
      opacity: 0.6;
    }
  }

  .position-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin-top: 20rpx;
  }

  .position-option {
    display: flex;
    align-items: center;
    gap: 16rpx;
    padding: 16rpx 0;
    font-size: 28rpx;
    color: #333;
  }

  .position-text {
    font-size: 28rpx;
    color: #333;
  }

  .selected-positions {
    margin-top: 20rpx;
    padding: 20rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
  }

  .selected-text {
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
  }
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.popup-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 40rpx 30rpx;
  z-index: 1000;

  .popup-title {
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }

  .popup-message {
    font-size: 28rpx;
    color: #606266;
    line-height: 1.6;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .popup-btn {
    width: 60%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    background-color: #1989fa;
    color: #fff;
    font-size: 30rpx;
  }
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20rpx 0;
}

.qr-code-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 20rpx;
}

.qr-code-tip {
  font-size: 28rpx;
  color: #606266;
  text-align: center;
}

.agreement-label {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.agreement-text {
  font-size: 26rpx;
  color: #606266;
  margin-left: 10rpx;
}
</style>
